import 'package:cached_network_image/cached_network_image.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:event_bus/event_bus.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/views/search_appbar.dart';

import '../entity/product_entity.dart';
import '../http/api.dart';
import '../routers/routers.dart';
import '../utils/common_utils.dart';
import '../utils/event_msg.dart';
import '../utils/singleton_manager.dart';
import '../views/dialog_manager.dart';

///
/// 店铺主页的第二分页
///
class MallHomeProductsPage extends StatefulWidget {
  var storeId = '';

  MallHomeProductsPage({Key? key, this.storeId = ''}) : super(key: key);

  @override
  State<MallHomeProductsPage> createState() => _MallHomeProductsPageState();
}

class _MallHomeProductsPageState extends State<MallHomeProductsPage> {
  var _menuIndex = 1;

  //可选值all(综合排序), price（价格排序 默认值）,sales(销量排序)
  var order_by = 'all';

  var sort = 'desc';

  var keyWord = '';

  List<ProductData> datas = [];
  var page = 1;

  getProducts() async {
    var param = {
      'page': page.toString(),
      'size': '20',
      'order_by': order_by,
      'store_id': widget.storeId
    };
    if (order_by == 'price') {
      param['sort'] = sort;
    }
    if (keyWord.isNotEmpty) {
      param['keyword'] = keyWord;
    }
    dynamic result = await Api.goodsList(param);
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getProducts();

    SingletonManager.instance.eventBus.on<StoreSearch>().listen((event) {
      // print(event.keyWord);
      keyWord = event.keyWord;
      page = 1;
      getProducts();
    });
  }

  //返回商品列表item
  getListItem(int index) {
    return Container(
      height: 180.w,
      margin: EdgeInsets.symmetric(horizontal: 5.w, vertical: 0.w),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Config.colorDivider, width: 2.w),
        ),
      ),
      child: InkWell(
        onTap: () {
          Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
        },
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(left: 20.w, right: 20.w),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  imageUrl: CommonUtils.compressImageUrl(datas[index].mainImg, 250, 250),
                  fit: BoxFit.fill,
                  width: 140.w,
                  height: 140.w,
                  errorWidget: (context, url, error) {
                    return Image.asset(
                      'assets/images/bg_default_400.png',
                      width: 140.w,
                      height: 140.w,
                      fit: BoxFit.fill,
                    );
                  },
                ),
              ),
            ),
            Container(
              height: 140.w,
              width: 480.w,
              child: Stack(
                children: [
                  Text(
                    datas[index].name,
                    softWrap: true,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: (Config.colorText1), fontSize: 22.w),
                  ),
                  Positioned(
                    bottom: 32.w,
                    child: Text(
                      "已售 ${datas[index].salesNum}",
                      style: TextStyle(fontSize: 20.sp, color: Config.colorText1),
                    ),
                  ),
                  Positioned(
                    bottom: 0.w,
                    child: Text(
                      CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                          datas[index].money1, datas[index].company1),
                      style: TextStyle(fontSize: 20.sp, color: Colors.red),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: Stack(
          children: [
            Container(
              height: 80.w,
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: Config.colorDivider, width: 2.w),
                ),
              ),
              width: double.infinity,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  InkWell(
                    onTap: () {
                      setState(() {
                        _menuIndex = 1;
                        order_by = 'all';
                        page = 1;
                        getProducts();
                      });
                    },
                    child: Container(
                      width: 76.w,
                      child: Text(
                        '综合',
                        style: TextStyle(
                            fontSize: 25.sp,
                            color: _menuIndex == 1 ? Config.colorMain : Config.colorText1),
                      ),
                    ),
                  ),
                  InkWell(
                    onTap: () {
                      setState(() {
                        _menuIndex = 2;
                        order_by = 'sales';
                        page = 1;
                        getProducts();
                      });
                    },
                    child: Text(
                      '销量',
                      style: TextStyle(
                          fontSize: 25.sp,
                          color: _menuIndex == 2 ? Config.colorMain : Config.colorText1),
                    ),
                  ),
                  Stack(
                    children: [
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (_menuIndex == 3) {
                              _menuIndex = 4;
                              sort = 'asc';
                            } else {
                              _menuIndex = 3;
                              sort = 'desc';
                            }
                            order_by = 'price';
                            page = 1;
                            getProducts();
                          });
                        },
                        child: Container(
                          width: 76.w,
                          child: Text(
                            '价格',
                            style: TextStyle(
                                fontSize: 25.sp,
                                color: (_menuIndex == 3 || _menuIndex == 4)
                                    ? Config.colorMain
                                    : Config.colorText1),
                          ),
                        ),
                      ),
                      Visibility(
                        visible: _menuIndex == 3 || _menuIndex == 4,
                        child: Container(
                          width: 76.w,
                          height: 37.w,
                          alignment: Alignment.centerRight,
                          child: Image.asset(
                            _menuIndex == 3
                                ? 'assets/images/icon_price_desc.png'
                                : 'assets/images/icon_price_ase.png',
                            width: 20.w,
                            height: 25.w,
                            color: Config.colorMain,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Container(
              height: double.infinity,
              width: double.infinity,
              margin: EdgeInsets.only(top: 80.w),
              child: EasyRefresh(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  await Future.delayed(const Duration(milliseconds: 200), () {
                    page = 1;
                    getProducts();
                  });
                },
                onLoad: () async {
                  getProducts();
                },
                child: ListView.builder(
                  itemCount: datas.length,
                  // shrinkWrap: true,
                  // scrollDirection: Axis.vertical,
                  // physics: const BouncingScrollPhysics(),
                  itemBuilder: (BuildContext context, int index) {
                    return getListItem(index);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
